<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .tdContents {
        max-width: 200px;
        word-wrap: break-word;
      }
    </style>
  </head>

  <body>
    <div id="app">
      <!-- 用户输入评论 -->
      <textarea cols="30" rows="10" @blur="textFn" :value="val"> </textarea>

      <button @click="subFn">发布评论</button>
      <!-- 渲染用户的评论 -->
      <table border="1" cellspacing="0" cellpadding="5">
        <tr>
          <th>游客</th>
          <th>评论</th>
          <th>点赞数</th>
          <th>发布日期</th>
          <th colspan="3">操作</th>
        </tr>
        <tr v-for="(item,index) in list">
          <!-- 游客 -->
          <td><span>{{item.name}}</span></td>
          <!-- 评论 -->
          <td class="tdContents"><span>{{item.contents}}</span></td>
          <!-- 点赞数 -->
          <td><span>{{item.count}}</span></td>
          <!-- 发布日期 -->
          <td><span>{{item.time}}</span></td>
          <!-- 点赞 -->
          <td><button @click="item.count+=1">点赞</button></td>
          <!-- 置顶 -->
          <td><button @click="topFn(item,index)">置顶</button></td>
          <!-- 删除 -->
          <td><button @click="delFn(item,index)">删除</button></td>
        </tr>
      </table>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
    <script>
      let vm = new Vue({
        el: "#app",
        data: {
          val: "",
          list: [
            {
              id: 1,
              name: "茄子",
              contents: "住在山里面,真不错~",
              count: 999,
              time: "2021-10-11",
            },
            {
              id: 2,
              name: "大司马",
              contents: "芜湖起飞~",
              count: 0,
              time: "2021-10-12",
            },
            // {
            //     id:3,
            //     name:xxx,
            //     contents:,
            //     count:0,
            // }
          ],
        },
        methods: {
          //置顶
          topFn($item, $index) {
            this.list.splice($index, 1);
            this.list.unshift($item);
          },

          //删除
          delFn($item) {
            this.list.splice(this.list.indexOf($item), 1);
          },

          //评论
          textFn(event) {
            console.log(event.target.value);
            this.val = event.target.value;
          },

          //提交
          subFn() {
            this.list.push({
              id: Date.now(),
              name: "1111",
              contents: this.val,
              count: 0,
              time: new Date().toLocaleDateString().replace(/\//g, "-"),
            });

            //清空评论框内容
            this.val = "";
          },
        },
      });
    </script>
  </body>
</html>
